# coding=utf-8
from flask import *
import time
import logging

# run command(debug auto restart if the code is changed) :
# FLASK_APP=flasktest.py FLASK_DEBUG=1 flask run --host 0.0.0.0
# FLASK_APP=flasktest.py  flask run --host 0.0.0.0
app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG,
                    filename="log.log",
                    filemode="w",
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    )


# path  index
@app.route('/', methods=['GET'])
def index():
    return 'Hello, World!'


@app.route("/files/")
def files():
    """
    后缀斜线可以自行脑补，如果输入没有斜线的话;
    如果route没有斜线后缀，请求时却加上的话，会跪.
    """
    return "This is page files/"


"""
url变量部分作为入参
可指定变量类型：
string：	accepts any text without a slash (the default)
int：	accepts integers
float：	like int but for floating point values
path：	like the default but also accepts slashes
any：	matches one of the items provided
uuid：	accepts UUID strings
默认是string
"""


@app.route("/user/<username>/age=<int:age>")
def user(username, age):
    return "username is %s,age is %d" % (username, age)


@app.route("/search?<key>")
def search(key):
    return "Your are searching %s" % key


# redirect and function url_for()
@app.route("/redirect")
def redirect_to():
    return redirect(url_for("index"))


@app.route('/cookies')
def cookie_test():
    lastvisit = request.cookies.get("lastvisit")
    visitcount = request.cookies.get("visitcount")
    if visitcount is None:
        visitcount = 0
    visitcount = int(visitcount) + 1
    response = make_response("last visit is %s,summary visited times is %d." % (lastvisit, visitcount))
    response.set_cookie("lastvisit", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    response.set_cookie("visitcount", str(visitcount))
    return response


@app.route('/session')
def session_test():
    if 'username' in session:
        return 'Last visit is as  %s.' % escape(session['username'])
    else:
        session['username'] = 'Waooo'
        return 'First visit.'


@app.route('/sessionlogin', methods=['GET', 'POST'])
def session_login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        # return redirect(url_for('index'))
        return 'session'
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''


@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))


@app.route('/getpic')
def get_pic():
    return redirect(url_for('static', filename='test.jpg'))


@app.route('/rendertemplate/<name>')
def rendertemplate(name):
    return render_template('hello.html', name=name)


@app.route('/login/abort')
def abort_login():
    abort(401)


@app.errorhandler(404)
def page_not_found(error):
    logging.debug('A value for debugging')
    return render_template('page_not_found.html'), 404
    # return redirect(url_for('index'))
